<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="form-inline">
        <el-form-item label="用户名">
          <el-input v-model="queryParams.userName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增管理员</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-table
      v-loading="loading"
      :data="userList"
      border
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="userName" label="用户名" min-width="120" />
      <el-table-column label="头像" width="100" align="center">
        <template #default="scope">
          <el-avatar 
            v-if="scope.row.avatar" 
            :src="getImageUrl(scope.row.avatar)" 
            :size="40"
          />
          <el-avatar v-else :size="40" icon="UserFilled" />
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="120" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="220" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleView(scope.row)">查看</el-button>
          <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            :type="scope.row.status === 1 ? 'danger' : 'success'" 
            size="small" 
            @click="handleToggleStatus(scope.row)"
          >
            {{ scope.row.status === 1 ? '停用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 用户详情对话框 -->
    <el-dialog
      title="管理员详情"
      v-model="detailDialogVisible"
      width="500px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="用户ID">{{ detailForm.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ detailForm.userName }}</el-descriptions-item>
        <el-descriptions-item label="头像">
          <el-avatar 
            v-if="detailForm.avatar" 
            :src="getImageUrl(detailForm.avatar)" 
            :size="60"
          />
          <el-avatar v-else :size="60" icon="UserFilled" />
        </el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detailForm.phone }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailForm.status === 1 ? 'success' : 'danger'">
            {{ detailForm.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailForm.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailForm.updateTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 新增/编辑管理员对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="formDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :limit="1"
            list-type="picture"
            :file-list="fileList"
          >
            <el-button type="primary">选择头像</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过2MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdminList, getAdminDetail, saveOrUpdateAdmin } from '@/api/user'
import { handlePageResponse } from '@/utils/pagination'

// 用户列表
const userList = ref([])
// 总数据量
const total = ref(0)
// 加载状态
const loading = ref(false)
// 表单提交加载状态
const submitLoading = ref(false)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  phone: ''
})

// 用户详情表单
const detailForm = ref({})
// 用户详情对话框可见性
const detailDialogVisible = ref(false)

// 表单数据
const form = reactive({
  id: null,
  userName: '',
  password: null,
  phone: '',
  avatar: '',
  status: 1
})

// 表单对话框标题
const dialogTitle = ref('新增管理员')
// 表单对话框可见性
const formDialogVisible = ref(false)
// 表单引用
const formRef = ref(null)
// 头像上传文件列表
const fileList = ref([])
// 上传URL
const uploadUrl = '/api/file/uploadImage/user'

// 表单校验规则
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 4, message: '密码长度不能小于4位', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  return `/api/file/download?fileName=${imagePath}`
}

// 初始化数据
onMounted(async () => {
  await fetchData()
})

// 获取用户列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getAdminList(queryParams)
    const { list, total: totalCount } = handlePageResponse(res)
    userList.value = list
    total.value = totalCount
  } catch (error) {
    console.error('获取管理员列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchData()
}

// 重置查询
const resetQuery = () => {
  queryParams.userName = ''
  queryParams.phone = ''
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNum = 1
  fetchData()
}

// 处理查看用户详情
const handleView = (row) => {
  detailForm.value = { ...row }
  detailDialogVisible.value = true
}

// 处理添加用户
const handleAdd = () => {
  resetForm()
  fileList.value = []
  formDialogVisible.value = true
}

// 处理编辑用户
const handleEdit = (row) => {
  getAdminDetail(row.id).then(res => {
    if (res.code === 200) {
      form.id = res.data.id
      form.userName = res.data.userName
      form.password = null // 编辑时不填充密码
      form.phone = res.data.phone
      form.avatar = res.data.avatar
      form.status = res.data.status
      
      dialogTitle.value = '编辑管理员'
      // 编辑时不强制验证密码
      rules.password = []
      fileList.value = form.avatar ? [{
        name: '头像',
        url: getImageUrl(form.avatar)
      }] : []
      formDialogVisible.value = true
    }
  }).catch(error => {
    console.error('获取用户详情失败:', error)
  })
}

// 处理状态切换
const handleToggleStatus = (row) => {
  const statusText = row.status === 1 ? '停用' : '启用'
  ElMessageBox.confirm(
    `确认${statusText}管理员 "${row.userName}" 吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const newStatus = row.status === 1 ? 0 : 1
      const updateData = { ...row, status: newStatus }
      await saveOrUpdateAdmin(updateData)
      ElMessage({
        type: 'success',
        message: `${statusText}成功!`
      })
      await fetchData()
    } catch (error) {
      console.error('更新用户状态失败:', error)
    }
  }).catch(() => {
    // 取消操作
  })
}

// 上传前验证
const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('头像只能是JPG或PNG格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过2MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleAvatarSuccess = (response, file) => {
  if (response.code === 200) {
    form.avatar = response.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.userName = ''
  form.password = ''
  form.phone = ''
  form.avatar = ''
  form.status = 1
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      await saveOrUpdateAdmin(form)
      ElMessage({
        type: 'success',
        message: form.id ? '更新成功!' : '添加成功!'
      })
      formDialogVisible.value = false
      await fetchData()
    } catch (error) {
      console.error('保存管理员失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.avatar-uploader {
  margin-bottom: 10px;
}
</style> 